
package com.yami.shop.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.enums.InteractPowerEnum;
import com.yami.shop.bean.model.Blog;
import com.yami.shop.bean.model.UserSecurityConfig;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ResponseEnum;
import com.yami.shop.dao.BlogMapper;
import com.yami.shop.dao.UserSecurityConfigMapper;
import com.yami.shop.service.UserSecurityConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


/**
 * @author lgh on 2018/09/11.
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserSecurityConfigServiceImpl extends ServiceImpl<UserSecurityConfigMapper, UserSecurityConfig> implements UserSecurityConfigService {

    private final UserSecurityConfigMapper userSecurityConfigMapper;

    private final BlogMapper blogMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByUserId(UserSecurityConfig userSecurityConfig) {
        if (Objects.nonNull(userSecurityConfig.getComment())) {
            InteractPowerEnum instance = InteractPowerEnum.instance(userSecurityConfig.getComment());
            if (Objects.isNull(instance)) {
                throw new YamiShopBindException(ResponseEnum.SHOW_FAIL, "设置失败，稍后重试！");
            }
            UserSecurityConfig securityConfig = userSecurityConfigMapper.selectOne(Wrappers.lambdaQuery(UserSecurityConfig.class).eq(UserSecurityConfig::getUserId, userSecurityConfig.getUserId()));
            if (!userSecurityConfig.getComment().equals(securityConfig.getComment())) {
                // 同步个人动态的评论权限
                LambdaUpdateWrapper<Blog> wrapper = Wrappers.lambdaUpdate(Blog.class)
                        .set(Blog::getOpenComment, userSecurityConfig.getComment())
                        .eq(Blog::getArticleSource, 1).eq(Blog::getUserUid, userSecurityConfig.getUserId());
                blogMapper.update(null, wrapper);
            }
        }
        userSecurityConfigMapper.updateByUserId(userSecurityConfig);
    }

    @Override
    public UserSecurityConfig getByUserId(String userId) {
        UserSecurityConfig one = getOne(Wrappers.lambdaQuery(UserSecurityConfig.class).eq(UserSecurityConfig::getUserId, userId));
        return one;
    }
}
